package mvc.utill;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import mvc.entity.ActionBean;

import org.apache.tomcat.util.codec.binary.StringUtils;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

public class Analysisdom {
	
	//把dom的数据封装到javabean
	public static Map<String, ActionBean> getBean(HttpServletRequest request){
		String realPath = request.getSession().getServletContext().getRealPath("\\");
		//String contextPath = request.get
		System.out.println(realPath);
		SAXBuilder saxBuilder = new SAXBuilder();
		HashMap<String, ActionBean> actionMap = new HashMap<>();
		try {
			Document build = saxBuilder.build(new File(realPath+"\\WEB-INF\\"+"struts.xml"));
			Element rootElement = build.getRootElement();
			Element child1 = rootElement.getChild("beans");
			Element child2 = rootElement.getChild("action-mapping");
			List<Element> children = child1.getChildren();
			List<Element> children2 = child2.getChildren();
			for (Element e: children) {
				String pathValue=null;
				ActionBean actionBean = new ActionBean();
				String nameValue = e.getAttributeValue("name");
				actionBean.setName(nameValue);
				String classValue = e.getAttributeValue("class");
				actionBean.setActionclass(classValue);
				for (Element element : children2) {
					if (element.getAttributeValue("name").equals(nameValue)) {
						pathValue = element.getAttributeValue("path");
						actionBean.setPath(pathValue);
						String acClassValue = element.getAttributeValue("class");
						actionBean.setActionForm(acClassValue);
						List<Element> children3 = element.getChildren();
						HashMap<String, String> hashMap=new HashMap<>();
						for (Element element2 : children3) {
							String attributeValue = element2.getAttributeValue("name");
							String attributeValue2 = element2.getAttributeValue("value");
							hashMap.put(attributeValue, attributeValue2);
						}
						actionBean.setMap(hashMap);
					}else {
						 throw new Exception("mapping错误");
					}
				}
				actionMap.put(pathValue, actionBean);
			}			
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		//System.out.println(substring);
		
		
		return actionMap;
		
	}
	public static void main(String[] args) {
		
	}
}
